package admin

import (
	"invitation/internal/application"
	"invitation/internal/http/middleware"
	"invitation/internal/http/utils"
	"invitation/internal/pojo/dto"

	"github.com/gofiber/fiber/v2"
)

func DeleteGameEndpoint(application *application.Application) func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		gameReq := ctx.Locals(middleware.LocalKeysGameCreateRequest).(*dto.GamePayload)
		if gameReq.ID == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "id is required",
			})
		}
		id, err := utils.StringToUint(gameReq.ID)
		if err != nil {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "id is invalid",
			})
		}
		txCtx, err := application.RepoManager().BeginTx(ctx.Context())
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		defer func() {
			if err != nil {
				application.RepoManager().RollbackTx(txCtx)
			} else {
				application.RepoManager().CommitTx(txCtx)
			}
		}()
		if err := application.RepoManager().GameInfoRepo().Delete(id); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		if err := application.RepoManager().GameIntroductionRepo().Delete(id); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		if err := application.RepoManager().GameTheoryRepo().Delete(id); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		return ctx.Status(200).JSON(fiber.Map{
			"message": "success",
		})
	}
}
